import { geoMercator } from 'd3-geo';
import * as turf from '@turf/turf';

export function loadTexture(url) {
  const texture = new THREE.TextureLoader().load(url);
  texture.colorSpace = THREE.SRGBColorSpace;
  return texture;
}

export function assignUVs(geometry) {
  geometry.computeBoundingBox();

  const { max, min } = geometry.boundingBox;
  const offset = new THREE.Vector2(0 - min.x, 0 - min.y);
  const range = new THREE.Vector2(max.x - min.x, max.y - min.y);
  const uvAttribute = geometry.getAttribute('uv');
  const uvArray = uvAttribute.array;

  for (let i = 0; i < uvAttribute.count; i++) {
    const x = 2 * i;
    const y = x + 1;

    uvArray[x] = (uvArray[x] + offset.x) / range.x;
    uvArray[y] = (uvArray[y] + offset.y) / range.y;
  }

  uvAttribute.needsUpdate = true;
}

export function getProjection(data, baseSize) {
  const center = turf.getCoord(turf.center(data));
  const projection = geoMercator().center(center).scale(1).translate([0, 0]);

  const bbox = turf.bbox(data);
  const [x, y] = projection(bbox.slice(0, 2));
  const size = Math.max(Math.abs(x), Math.abs(y)) * 2;
  const base = baseSize || 40;
  const scale = base / size;
  projection.scale(scale);

  return (...args) => {
    const [x, y] = projection(...args);
    return [x, -y];
  };
}

export function log(...message) {
  console.log('%c ---------- base-three ----------', 'color: blue');
  console.log(...message);
  console.log('%c --------------------------------', 'color: blue');
}
